<script lang="ts" setup>
import type { CommentApi } from '#/api/wedding/comment';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Avatar, Button, Image, message, Rate, Tag } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

import { useVbenForm } from '#/adapter/form';
import { getComment, updateComment } from '#/api/wedding/comment';

import { useEditFormSchema } from '../data';

const emit = defineEmits(['success']);
const commentData = ref<CommentApi.Comment>();
const parentCommentData = ref<CommentApi.Comment>();

const getTitle = computed(() => {
  if (!commentData.value?.id) return '新增评论';
  return commentData.value.parentId ? '编辑回复' : '编辑评论';
});

// 判断是否为回复
const isReply = computed(() => {
  return !!commentData.value?.parentId;
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'w-full',
    labelWidth: 120,
  },
  layout: 'horizontal',
  schema: useEditFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    modalApi.lock();
    try {
      const data = (await formApi.getValues()) as CommentApi.Comment;
      await updateComment(data);
      await modalApi.close();
      emit('success');
      message.success('评论更新成功');
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      commentData.value = undefined;
      parentCommentData.value = undefined;
      return;
    }

    const data = modalApi.getData<CommentApi.Comment>();
    if (!data) {
      return;
    }

    commentData.value = data;

    // 如果是回复，加载父评论
    if (data.parentId) {
      try {
        parentCommentData.value = await getComment(data.parentId);
      } catch (error) {
        console.error('加载父评论失败:', error);
      }
    }

    await formApi.setValues(commentData.value);
  },
});

// 状态标签
function getStatusTag(status: string) {
  const statusMap: Record<string, { color: string; text: string }> = {
    approved: { color: 'green', text: '已通过' },
    deleted: { color: 'gray', text: '已删除' },
    pending: { color: 'orange', text: '待审核' },
    rejected: { color: 'red', text: '已拒绝' },
  };
  return statusMap[status] || { color: 'default', text: status };
}

// 格式化目标类型
function formatTargetType(type: string) {
  const typeMap: Record<string, string> = {
    dress: '婚纱',
    makeupartist: '化妆师',
    package: '套餐',
    photographer: '摄影师',
  };
  return typeMap[type] || type;
}

// 格式化时间
function formatTime(time: number | string) {
  const date = typeof time === 'number' ? new Date(time) : new Date(time);
  return date.toLocaleString('zh-CN');
}

// 跳转到评论目标页面
function goToTarget() {
  if (!commentData.value) return;

  const { targetType, targetId } = commentData.value;

  let path = '';
  switch (targetType) {
    case 'dress': {
      path = `/wedding/dress-preview/${targetId}`;
      break;
    }
    case 'makeupartist': {
      path = `/wedding/makeupartist/detail/${targetId}`;
      break;
    }
    case 'package': {
      path = `/wedding/package/detail/${targetId}`;
      break;
    }
    case 'photographer': {
      path = `/wedding/photographer/detail/${targetId}`;
      break;
    }
    default: {
      message.warning('未知的目标类型');
      return;
    }
  }

  // 在新标签页打开
  window.open(path, '_blank');
}
</script>

<template>
  <Modal :title="getTitle" width="900px" class="comment-detail-modal">
    <div v-if="commentData" class="space-y-6">
      <!-- 父评论引用（仅回复时显示） -->
      <div v-if="isReply && parentCommentData" class="relative">
        <div
          class="rounded-xl border-2 border-dashed border-gray-300 bg-gray-50 p-4"
        >
          <div class="mb-3 flex items-center gap-2">
            <IconifyIcon
              icon="lucide:corner-down-right"
              class="text-lg text-blue-500"
            />
            <span class="text-sm font-semibold text-gray-700"
              >回复的主评论</span
            >
          </div>

          <div class="rounded-lg border border-gray-200 bg-white p-4">
            <div class="mb-3 flex items-center gap-3">
              <Avatar :src="parentCommentData.userAvatar" :size="36">
                {{ parentCommentData.userName?.charAt(0) }}
              </Avatar>
              <div>
                <div class="font-medium text-gray-900">
                  {{ parentCommentData.userName }}
                </div>
                <div class="mt-1 flex items-center gap-2">
                  <Rate
                    :value="parentCommentData.rating"
                    disabled
                    size="small"
                  />
                  <span class="text-xs text-gray-500"
                    >{{ parentCommentData.rating }}星</span
                  >
                </div>
              </div>
            </div>
            <p class="pl-12 text-sm leading-relaxed text-gray-700">
              {{ parentCommentData.content }}
            </p>
            <div class="mt-2 pl-12 text-xs text-gray-400">
              {{ formatTime(parentCommentData.createTime) }}
            </div>
          </div>

          <div class="absolute -bottom-3 left-1/2 -translate-x-1/2 transform">
            <div
              class="rounded-full bg-blue-500 px-3 py-1 text-xs font-medium text-white shadow-md"
            >
              <IconifyIcon icon="lucide:arrow-down" class="inline" />
              回复如下
            </div>
          </div>
        </div>
      </div>

      <!-- 当前评论信息卡片 -->
      <div
        class="rounded-xl border border-blue-100 bg-gradient-to-r from-blue-50 to-purple-50 p-5"
        :class="{ 'mt-8': isReply }"
      >
        <!-- 回复标识 -->
        <div v-if="isReply" class="mb-3 flex items-center gap-2 text-blue-600">
          <IconifyIcon icon="lucide:reply" class="text-lg" />
          <span class="text-sm font-medium">
            这是一条回复
            <span v-if="commentData.replyToUser" class="text-gray-600">
              （回复给 <strong>@{{ commentData.replyToUser }}</strong
              >）
            </span>
          </span>
        </div>

        <div class="mb-4 flex items-start justify-between">
          <div class="flex items-center gap-3">
            <Avatar :src="commentData.userAvatar" :size="48">
              {{ commentData.userName?.charAt(0) }}
            </Avatar>
            <div>
              <div class="text-base font-semibold text-gray-900">
                {{ commentData.userName }}
              </div>
              <div class="mt-1 flex items-center gap-2">
                <Rate
                  v-if="commentData.rating > 0"
                  :value="commentData.rating"
                  disabled
                  size="small"
                />
                <span
                  v-if="commentData.rating > 0"
                  class="text-sm text-gray-500"
                  >{{ commentData.rating }}星</span
                >
                <span v-else class="text-xs text-gray-400">回复无评分</span>
              </div>
            </div>
          </div>
          <Tag
            :color="getStatusTag(commentData.status).color"
            class="px-3 py-1 text-sm"
          >
            {{ getStatusTag(commentData.status).text }}
          </Tag>
        </div>

        <div class="rounded-lg bg-white p-4 shadow-sm">
          <div class="mb-2 text-sm text-gray-500">评论内容</div>
          <p class="whitespace-pre-wrap leading-relaxed text-gray-800">
            {{ commentData.content }}
          </p>
        </div>

        <!-- 评论图片 -->
        <div
          v-if="commentData.images && commentData.images.length > 0"
          class="mt-3"
        >
          <div class="mb-2 text-sm text-gray-500">评论图片</div>
          <div class="rounded-lg bg-white p-3">
            <Image.PreviewGroup>
              <Image
                v-for="(img, index) in commentData.images"
                :key="index"
                :src="img"
                :width="80"
                :height="80"
                class="mb-2 mr-2 rounded object-cover"
              />
            </Image.PreviewGroup>
          </div>
        </div>

        <!-- 互动数据 -->
        <div class="mt-3 flex flex-wrap items-center gap-4 text-sm">
          <!-- 评论目标（可点击跳转） -->
          <Button
            type="default"
            size="small"
            class="flex items-center gap-1"
            @click="goToTarget"
          >
            <template #icon>
              <IconifyIcon icon="lucide:external-link" class="text-blue-500" />
            </template>
            查看{{ formatTargetType(commentData.targetType) }} #{{
              commentData.targetId
            }}
          </Button>
          <div class="flex items-center gap-1 rounded-lg bg-white px-3 py-1.5">
            <IconifyIcon icon="lucide:heart" class="text-red-500" />
            <span class="text-gray-500">点赞：</span>
            <span class="font-medium text-red-500">{{
              commentData.likeCount || 0
            }}</span>
          </div>
          <div
            v-if="!isReply"
            class="flex items-center gap-1 rounded-lg bg-white px-3 py-1.5"
          >
            <IconifyIcon icon="lucide:message-circle" class="text-blue-500" />
            <span class="text-gray-500">回复：</span>
            <span class="font-medium text-blue-500">{{
              commentData.replyCount || 0
            }}</span>
          </div>
          <div class="flex items-center gap-1 rounded-lg bg-white px-3 py-1.5">
            <IconifyIcon icon="lucide:clock" class="text-gray-400" />
            <span class="text-gray-500">时间：</span>
            <span class="font-medium">{{
              formatTime(commentData.createTime)
            }}</span>
          </div>
        </div>
      </div>

      <!-- 编辑表单 -->
      <div class="rounded-xl border border-gray-200 bg-white p-5">
        <h3
          class="mb-4 flex items-center gap-2 text-base font-semibold text-gray-900"
        >
          <span class="h-5 w-1 rounded bg-blue-500"></span>
          管理员编辑
        </h3>
        <Form />
        <div class="mt-4 rounded-lg border border-yellow-200 bg-yellow-50 p-3">
          <div class="text-sm text-yellow-800">
            <strong>提示：</strong>
            <ul class="ml-4 mt-1 list-disc space-y-1">
              <li>只能编辑评论内容、评分和状态</li>
              <li>用户信息、目标信息等不可修改</li>
              <li>修改后会记录操作日志</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </Modal>
</template>

<style scoped>
.space-y-6 > * + * {
  margin-top: 1.5rem;
}
</style>
